package cn.iocoder.yudao.module.forward.controller.app.register;

import cn.iocoder.yudao.module.forward.controller.app.register.vo.*;
import cn.iocoder.yudao.module.forward.dal.dataobject.group.GroupDO;
import cn.iocoder.yudao.module.forward.dal.dataobject.license.LicenseDO;
import cn.iocoder.yudao.module.forward.service.group.GroupService;
import cn.iocoder.yudao.module.forward.service.license.LicenseService;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;

@Tag(name = "终端注册 APP - 注册接口")
@RestController
@RequestMapping("/register")
@Validated
public class RegisterController {
    @Resource
    private LicenseService licenseService;
    @Resource
    private GroupService groupService;

    @PostMapping("/tm_register")
    @Operation(summary = "终端注册")
    @PermitAll
    public String tm_register(HttpServletRequest request) throws IOException {
        ResultRespVO resultRespVO = new ResultRespVO();

        RegisterReqVO registerReqVO = null;
        if("application/x-www-form-urlencoded".equals(request.getContentType())){
            registerReqVO = new RegisterReqVO();
            registerReqVO.setLicense(request.getParameter("license"));
            registerReqVO.setOwner(request.getParameter("owner"));
            registerReqVO.setType(request.getParameter("type"));

        }else if("application/json".equals(request.getContentType())){
            ObjectMapper mapper = new ObjectMapper();
            registerReqVO = mapper.readValue(request.getInputStream(), RegisterReqVO.class);
        }else{
            resultRespVO.setResult("请求content-type错误");
            return JSONObject.toJSONString(resultRespVO);
        }


        LicenseDO licenseDO = licenseService.getLicenseRegister(registerReqVO);
        if(licenseDO==null){
            resultRespVO.setResult("未查询到注册信息");
            return JSONObject.toJSONString(resultRespVO);
        }else{
            if(licenseDO.getRegistered()==true){
                resultRespVO.setResult("设备已注册");
                return JSONObject.toJSONString(resultRespVO);
            }

            RegisterRespVO data = new RegisterRespVO();
            data.setClientId(licenseDO.getClientId());
            data.setUname(licenseDO.getUname());
            data.setPwd(licenseDO.getPwd());
            data.setGroupId(groupService.getGroup(licenseDO.getGroupId()).getCode());
            resultRespVO.setResult(data);

            licenseDO.setRegistered(true);
            licenseDO.setRegisterTime(LocalDateTime.now());
            licenseService.updateById(licenseDO);

            return JSONObject.toJSONString(resultRespVO);
        }
    }

    @PostMapping("/tm_altertinfo")
    @Operation(summary = "变更注册")
    @PermitAll
    public ResultRespVO tm_altertinfo(HttpServletRequest request) throws IOException {
        ResultRespVO resultRespVO = new ResultRespVO();

        AltertInfoReqVO altertInfoReqVO = null;
        if("application/x-www-form-urlencoded".equals(request.getContentType())){
            altertInfoReqVO = new AltertInfoReqVO();
            altertInfoReqVO.setClientId(request.getParameter("clientId"));
            altertInfoReqVO.setOwner(request.getParameter("owner"));
            altertInfoReqVO.setType(request.getParameter("type"));
            altertInfoReqVO.setUname(request.getParameter("uname"));
            altertInfoReqVO.setPwd(request.getParameter("pwd"));
            altertInfoReqVO.setAlterinfo(request.getParameter("alterinfo"));
        }else if("application/json".equals(request.getContentType())){
            ObjectMapper mapper = new ObjectMapper();
            altertInfoReqVO = mapper.readValue(request.getInputStream(), AltertInfoReqVO.class);
        }else{
            resultRespVO.setResult("请求content-type错误");
            return resultRespVO;
        }

        LicenseDO licenseDO = licenseService.getLicenseRegister(altertInfoReqVO);
        if(licenseDO ==null){
            resultRespVO.setResult("未查询到设备信息");
            return resultRespVO;
        }else{
            String alterinfo = altertInfoReqVO.getAlterinfo()
                    .replaceAll(" ","")
                    .replaceAll("，",",")
                    .replaceAll("：",":").trim();
            String[] infos = alterinfo.split(",");
            HashMap<String,String> map = new HashMap<>();
            for(String info:infos){
                String[] parm = info.split(":");
                map.put(parm[0],parm[1]);
            }

            for (String key:map.keySet()){
                if(key.equals("groupId")){
                    GroupDO group = groupService.getGroupByCode(map.get(key));
                    if(group!=null){
                        licenseDO.setGroupId(group.getId());
                    }else{
                        resultRespVO.setResult("变更失败，未查询到分组");
                        return resultRespVO;
                    }
                }else if(key.equals("owner")){
                    licenseDO.setOwner(map.get(key));
                }else if(key.equals("type")){
                    licenseDO.setTypeCode(map.get(key));
                }else if(key.equals("pwd")){
                    licenseDO.setPwd(map.get(key));
                }
            }
            licenseService.updateById(licenseDO);
            resultRespVO.setResult("注册信息变更完毕");
            return resultRespVO;
        }
    }

    @PostMapping("/tm_suspend")
    @Operation(summary = "暂停/恢复")
    @PermitAll
    public String tm_suspend(HttpServletRequest request) throws IOException {
        ResultRespVO resultRespVO = new ResultRespVO();

        SuspendReqVO suspendReqVO = null;
        if("application/x-www-form-urlencoded".equals(request.getContentType())){
            suspendReqVO = new SuspendReqVO();
            suspendReqVO.setAction(Boolean.valueOf(request.getParameter("action")));
            suspendReqVO.setClientId(request.getParameter("clientId"));
            suspendReqVO.setUname(request.getParameter("uname"));
            suspendReqVO.setPwd(request.getParameter("pwd"));
        }else if("application/json".equals(request.getContentType())){
            ObjectMapper mapper = new ObjectMapper();
            suspendReqVO = mapper.readValue(request.getInputStream(), SuspendReqVO.class);
        }else{
            resultRespVO.setResult("请求content-type错误");
            return JSONObject.toJSONString(resultRespVO);
        }

        LicenseDO licenseDO = licenseService.getLicenseRegister(suspendReqVO);
        if(licenseDO ==null){
            resultRespVO.setResult("未查询到设备信息");
            return JSONObject.toJSONString(resultRespVO);
        }else{
            if(suspendReqVO.getAction()){
                resultRespVO.setResult("暂停成功");
                return JSONObject.toJSONString(resultRespVO);
            }else{
                resultRespVO.setResult("恢复成功");
                return JSONObject.toJSONString(resultRespVO);
            }
        }
    }
}
